package com.markhsiu.minimq.remote.transport.netty.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.markhsiu.minimq.client.CallBackCache;
import com.markhsiu.minimq.client.CallBackor;
import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.message.Result;
import com.markhsiu.minimq.message.constant.MessageCmdEnum;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by Mark Hsiu on 2017/2/8.
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter{
	private static Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	private static boolean isDebugEnabled = logger.isDebugEnabled();
	private CallBackor callBackor;
	
	public NettyClientHandler(CallBackor callBackor) {
		this.callBackor = callBackor ;
	}
	
    //管道链路激活
    @Override
    public void channelActive(ChannelHandlerContext channel) throws Exception {
    	 super.channelActive(channel);
    }

    // 当服务器端返回应答消息时，channelRead方法被调用，Netty的ByteBuf中读取并打印应答消息
    @Override
    public void channelRead(ChannelHandlerContext channel, Object msg) throws Exception {
        Message message = (Message) msg;
        if(isDebugEnabled){
        	 logger.debug("channelRead ... {}",message);
        }
       
        Result result =  CallBackCache.getCallBack(message.getMessageID());
        
        if(result != null){
        	result.setMessage(message);
            result.release();
        }
               
        if(callBackor != null){
        	
        	if(message.getCmd() == MessageCmdEnum.NEW){
        		result = new Result();
            	result.setMessage(message);
            	Message response = callBackor.print(result);
            	if(isDebugEnabled){
            		logger.debug("channelWrite ... {},"+response);
                }
            	channel.writeAndFlush(response);
        	}
        } 
    	
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext channel, Throwable cause) {
        // 释放资源
    	channel.close();
    }
}
